<?php


class Order extends AdminBase {

	public function index(){
		$page=$this->uri->segment(4);
        $where['order_status']=$this->GetId();
        
     	if ($this->post()){
     		$order_no=$this->input->post()['order_no'];
     		$data['list']=$this->db->like('order_no',$order_no,'both')->limit(10,$page)->where($where)->get('order')->result_array();
     		$count=$this->db->like('order_no',$order_no,'both')->where($where)->get('order')->result_array();
     	}else{
     		$data['list']=$this->db->limit(10,$page)->where($where)->get('order')->result_array();
     		$count=$this->db->where($where)->get('order')->result_array();
     	}

        foreach ($data['list'] as $k=>$v){
       	$info=$this->GetGoods($v['order_id']);
       	$data['list'][$k]['goods_name']=$info['goods_name'];
       	$data['list'][$k]['goods_num']=$info['goods_num'];
       	$data['list'][$k]['image']=$info['image'];
       	$data['list'][$k]['goods_price']=$info['goods_price'];
       	$data['list'][$k]['address']=$this->db->where('order_id',$v['order_id'])->get('order_address')->row_array();
       }
       
       	$this->load->library('pagination');
		$config['base_url'] = "/order/index/{$where['order_status']}/";
		$config['total_rows'] = count($count);
		$config['per_page'] =10;
		
		$this->pagination->initialize($config);
		$data['pages']=$this->pagination->create_links();
  
       $this->load->view('order/index',$data);
	}
	
	
	public function detail(){
		$order_id=(int)$this->uri->segment(3);
        $data['order']=$this->db->where('order_id',$order_id)->get('order')->row_array();
	    $data['address']=$this->db->where('order_id',$order_id)->get('order_address')->row_array();
	    $data['goods']=$this->GetAllGoods($order_id);
	    $data['express']=$this->db->get('express')->result_array();
	    $data['invoice']=$this->db->where('id',$data['order']['invoice'])->get('invoice')->row_array();
	    $this->load->view('order/detail',$data);
	}
	
	
	public function price(){
		$order_id=(int)$this->uri->segment(3);
        $data['order']=$this->db->where('order_id',$order_id)->get('order')->row_array();
		$this->load->view('order/price',$data);
	}
	
	
	public function doprice(){
		$post=$this->input->post();
		$data['pay_price']=$post['pay_price'];
		$res=$this->db->where('order_id',$post['order_id'])->update('order',$data);
		if($res){
			$this->show(array('code'=>1,'msg'=>'修改成功'));
		}else{
			$this->show(array('code'=>0,'msg'=>'修改失败'));	
		}
		
		
	}
	
	public function returns(){
		$order_id=(int)$this->uri->segment(3);
        $data['order']=$this->db->where('order_id',$order_id)->get('order')->row_array();
	    $data['address']=$this->db->where('order_id',$order_id)->get('order_address')->row_array();
	    $data['goods']=$this->GetAllGoods($order_id);
	    $data['express']=$this->db->get('express')->result_array();
	$this->load->view('order/returns',$data);
	}
	
	
	public function del(){
	$where['order_id']=$this->PostId();
	$this->db->trans_begin();
    $this->db->where($where)->delete('order');
    $this->db->where($where)->delete('order_address');
    $this->db->where($where)->delete('order_goods');
if ($this->db->trans_status() === FALSE){
    $this->db->trans_rollback();
      $this->show(array('code'=>0,'msg'=>'删除失败'));
}else{
    $this->db->trans_commit();
      $this->show(array('code'=>1,'msg'=>'删除成功'));
}
	}
	
	
	public function doreturn(){
		$post=$this->input->post();
		if($post['status']==10){
		$wxapp=$this->db->get('wxapp')->row_array();
        $transaction_id=$post['transaction_id']; 
        $total_fee=$post['pay_price'];
        $refund_fee=$post['pay_price'];

		// 当前时间
		$time = time();
		// 生成随机字符串
		$nonceStr = md5($time . $transaction_id . $total_fee . $refund_fee);
		// API参数
		$params = array(
			'appid' => $wxapp['AppID'],
			'mch_id' => $wxapp['mchid'],
			'nonce_str' => $nonceStr,
			'transaction_id' => $transaction_id,
			'out_refund_no' => $time,
			'total_fee' => $total_fee * 100,
			'refund_fee' => $refund_fee * 100,
		);

		// 生成签名
		$params['sign'] = $this->makeSign($params);
				

		// 请求API
		$url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
		$result = $this->posts($url, $this->toXml($params), true, $this->getCertPem()); 
		$prepay = $this->fromXml($result);
	
		// 请求失败
		if ($prepay['return_code'] === 'FAIL') {
			$this->show(array('code'=>0,'msg' => 'return_msg: ' . $prepay['return_msg']));
		}
		if ($prepay['result_code'] === 'FAIL') {
			$this->show(array('code'=>0,'msg' => 'err_code_des: ' . $prepay['err_code_des']));
		}
		
		    $where['order_id']=$post['order_id'];
		    $data['order_status']=50;
		    $this->db->where($where)->update('order',$data);
			$this->show(array('code'=>1,'msg' => '退款成功'));
		}
		
	}
	
	
		/**
	 * 获取cert证书文件
	 * @return array
	 * @throws BaseException
	 */
	private function getCertPem(){
		$wxapp=$this->db->get('wxapp')->row_array();
		// cert目录
		$filePath = __DIR__ . '/cert/';
		!is_dir($filePath) && mkdir($filePath, 0755, true);
		$certPem = $filePath . 'cert.pem';
		!file_exists($certPem) && file_put_contents($certPem, $wxapp['cert_pem']);
		$keyPem = $filePath . 'key.pem';
		!file_exists($keyPem) && file_put_contents($keyPem,$wxapp['key_pem']);
		return compact('certPem', 'keyPem');
	}

	
		/**
	 * 格式化参数格式化成url参数
	 * @param $values
	 * @return string
	 */
	private function toUrlParams($values){
		$buff = '';
		foreach ($values as $k => $v) {
			if ($k != 'sign' && $v != '' && !is_array($v)) {
				$buff .= $k . '=' . $v . '&';
			}
		}
		return trim($buff, '&');
	}


	
		/**
	 * 将xml转为array
	 * @param $xml
	 * @return mixed
	 */
	private function fromXml($xml){
		// 禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
	}
	/**
	 * 输出xml字符
	 * @param $values
	 * @return bool|string
	 */
	private function toXml($values){
		if (!is_array($values)
			|| count($values) <= 0
		) {
			return false;
		}

		$xml = "<xml>";
		foreach ($values as $key => $val) {
			if (is_numeric($val)) {
				$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
			} else {
				$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
			}
		}
		$xml .= "</xml>";
		return $xml;
	}
	
		/**
	 * 模拟POST请求
	 * @param $url
	 * @param array $data
	 * @param bool $useCert
	 * @param array $sslCert
	 * @return mixed
	 */
	public function posts($url, $data =array(), $useCert = false, $sslCert =array()){
		$header = array('Content-type: application/json;');
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_POST, TRUE);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		if ($useCert == true) {
			// 设置证书：cert 与 key 分别属于两个.pem文件
			curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
			curl_setopt($curl, CURLOPT_SSLCERT, $sslCert['certPem']);
			curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM');
			curl_setopt($curl, CURLOPT_SSLKEY, $sslCert['keyPem']);
		}
		$result = curl_exec($curl);
		curl_close($curl);
		return $result;
	}
	
		/**
	 * 生成签名
	 * @param $values
	 * @return string 本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
	 */
	private function makeSign($values)
	{
			$wxapp=$this->db->get('wxapp')->row_array();
		//签名步骤一：按字典序排序参数
		ksort($values);
		$string = $this->toUrlParams($values);
		//签名步骤二：在string后加入KEY
		$string = $string . '&key=' . $wxapp['apikey'];
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}
	
   public function deliver(){
   	 $post=$this->input->post();
   	 $express=$this->db->where('express_id',$post['express_id'])->get('express')->row_array();
   	 $data['order_status']=30;
   	 $data['deliver_time']=time();
   	 $data['express']=$express['express_name'];
   	 $data['express_code']=$express['express_code'];
   	 $data['number']=$post['number'];
   	 $where['order_id']=$post['order_id'];
   	 $res=$this->db->where($where)->update('order',$data);
   	 			if ($res){
				$this->show(array('code'=>1,'msg'=>'更新成功'));
			}else{
				$this->show(array('code'=>0,'msg'=>'无数据更新'));
			}
   	
   }
	
	public function GetGoods($order_id){
		$list=$this->db->where('order_id',$order_id)->get('order_goods')->row_array();
		return $list;
    	}
	
		public function GetAllGoods($order_id){
		$list=$this->db->where('order_id',$order_id)->get('order_goods')->result_array();
		return $list;
    	}
}
